<template>
  <el-dialog :visible.sync="visible" title="分享" :close-on-click-modal="false" :close-on-press-escape="false" append-to-body>
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmitHandle()" label-width="120px">
      <el-form-item label="文件名">
        {{fileData.fileName || ''}}
      </el-form-item>
      <template v-if="!fileData.sign || !shareUrl">
        <el-form-item prop="password" label="提取码">
          <el-input v-model="dataForm.password"></el-input>
        </el-form-item>
        <el-form-item prop="expireDay" label="有效时间(天)">
          <el-select v-model="dataForm.expireDay" placeholder="请选择" >
            <el-option
                v-for="item in expireDayList"
                :key="item.value"
                :label="item.text"
                :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
      </template>
      <template v-else>
        <el-form-item label="分享地址">
          {{shareUrl}}
        </el-form-item>
        <el-form-item label="提取码">
          {{fileData.password}}
        </el-form-item>
      </template>
    </el-form>
    <template slot="footer">
      <el-button @click="visible = false">关闭</el-button>
      <el-button type="primary" @click="dataFormSubmitHandle()" v-if="!fileData.sign || !shareUrl">创建连接</el-button>
      <el-button type="primary" @click="copyData()" v-else>复制连接</el-button>
    </template>
  </el-dialog>
</template>

<script>
import debounce from 'lodash/debounce'
export default {
  data () {
    return {
      visible: false,
      dataForm: {
        path: '',
        password: '',
        // 过期时间（天），-1=永久
        expireDay: 7
      },
      // 有效时间-选择源
      expireDayList: [
        { text: '1天', value: 1 },
        { text: '7天', value: 7 },
        { text: '30天', value: 30 },
        { text: '永久有效', value: -1 }
      ],
      fileData: {},
      // 分享地址
      shareUrl: '',
      // 数据加载标识
      dataListLoading: false
    }
  },
  computed: {
    dataRule () {
      return {
        password: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        expireDay: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    copyData () {
      this.copyHandle(`连接：${this.shareUrl}\n提取码：${this.fileData.password}`)
    },
    copyHandle (data) {
      const url = data
      const oInput = document.createElement('textarea')
      oInput.value = url
      document.body.appendChild(oInput)
      oInput.select() // 选择对象
      document.execCommand('Copy') // 执行浏览器复制命令
      document.body.removeChild(oInput)

      this.$message({
        message: '复制成功',
        type: 'success'
      })
      oInput.remove()
    },
    init () {
      this.visible = true
      this.$nextTick(() => {
        // this.$refs['dataForm'].resetFields()
        // this.dataForm.password=''
        this.fileData = {}
        this.dataForm.expireDay = 7
        this.getInfo()
      })
    },
    // 设置分享地址
    setShareUrl () {
      if (this.fileData.sign) {
        const curUrl = window.location.href
        const endIndex = curUrl.indexOf('#/')
        if (endIndex !== -1) {
          this.shareUrl = curUrl.substring(0, endIndex + 2) + 'share?sign=' + this.fileData.sign
        }
      }
    },
    // 获取信息
    getInfo () {
      this.dataListLoading = true
      this.dataForm.password = ''
      this.$http.get('/oss/share/getInfoByPath', {
        params: { path: this.dataForm.path }
      }).then(({ data: res }) => {
        this.dataListLoading = false
        if (res.code !== 0) {
          this.visible = false
          return this.$message.error(res.msg)
        }
        this.fileData = {
          ...this.fileData,
          ...res.data,
          ...(res.data || {}).shareFile
        }
        if (this.fileData.password) {
          this.dataForm.password = this.fileData.password
        }
        if (!this.dataForm.password) {
          this.dataForm.password = this.genPassword()
        }
        this.setShareUrl()
      }).catch(() => {
        this.visible = false
        this.dataListLoading = false
      })
    },
    genPassword () {
      const chars = '0A1B2C3D4E5F6G7H8I9J0K1L2M3N4O5P6Q7R8S9T0U1V2W3X4Y5Z6a7b8c9d0e1f2g3h4i5j6k7l8m9n0o1p2q3r4s5t6u7v8w9x0y1z0123456789'
      let result = ''
      for (let i = 0; i < 5; i++) {
        const index = Math.round(Math.random() * 114)
        result += chars.charAt(index) || ''
      }
      return result
    },
    // 表单提交
    dataFormSubmitHandle: debounce(function () {
      this.$refs.dataForm.validate((valid) => {
        if (!valid) {
          return false
        }
        this.$http.post('/oss/share/create', this.dataForm).then(({ data: res }) => {
          if (res.code !== 0) {
            return this.$message.error(res.msg)
          }
          this.fileData = {
            ...this.fileData,
            ...res.data
          }
          this.setShareUrl()
        }).catch(() => {})
      })
    }, 1000, { leading: true, trailing: false })
  }
}
</script>
